#include "wm6201.h"
#include "bitbind.h"
#include "rtos.h"
#include "uart.h"
#include "elog.h"
#include "string.h"
#include "delay.h"



#define WM6201_RST    PEout(7)

void wm6201_gpio_init(void)
{
	GPIO_InitTypeDef  GPIO_InitStructure;
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_Init(GPIOE, &GPIO_InitStructure);
	WM6201_RST=1;
}

void wm6201_init(void)
{
	wm6201_gpio_init();
}

void wm6201_hard_reset(void)
{
	WM6201_RST=1;
	//vTaskDelay(pdMS_TO_TICKS(1));
	delay_ms(1);
	WM6201_RST=0;
}

bool wm6201_enter_cmd_mode(void)
{
	u8 i=0;
	u16 wait_ms=0;
	u8 rx_buf[20]={0};
	u32 rx_cnt=0;
	uart_1.en_rx_timeout=true;
	
	for(i=0;i<5;i++)
	{
		uart_rx_fifo_clean(WM6201_UART);
		wm6201_send((u8*)"+++AT",5);
		for(wait_ms=1000;wait_ms;wait_ms--)
		{
			if(wm6201_get_cmd_ack_pcket(rx_buf,&rx_cnt,sizeof(rx_buf))==false)
			{
				vTaskDelay(pdMS_TO_TICKS(1));
				continue;
			}
			if((rx_cnt==1)&&(rx_buf[0]=='Y'))
			{
				log_d(" recv 'Y' ");
				goto STEP2;
			}
			else
			{
				log_d(" recv \"%s\" after send \"+++AT\" ",rx_buf);
			}
		}
		log_i(" recv 'Y' timeout ");
	}
	log_e(" enter cmd mode failed ");
	return false;
STEP2:
	uart_rx_fifo_clean(WM6201_UART);
	wm6201_send((u8*)"Y",1);
	for(wait_ms=2000;wait_ms;wait_ms--)
	{
		if(wm6201_get_cmd_ack_pcket(rx_buf,&rx_cnt,sizeof(rx_buf))==false)
		{
			vTaskDelay(pdMS_TO_TICKS(1));
			continue;
		}
		if(memcmp("AT+OK\r\n",rx_buf,7)==0)
		{
			log_d(" enter cmd mode ");
			goto STEP3;
		}
		else
		{
			log_d(" recv \"%s\" after send \"Y\" ",rx_buf);
		}
	}
	log_e(" recv \"AT+OK\" timeout,enter cmd mode failed ");
	return false;	
STEP3:
	if((wm6201_send_cmd((u8*)"AT+LOGIN=88888\r\n",sizeof("AT+LOGIN=88888\r\n"),NULL,rx_buf,&rx_cnt,1000)==0)&&(rx_cnt>=6))
	{
		if(memcmp("\r\nOK\r\n",&rx_buf[rx_cnt-6],6)!=0)
		{
			log_e(" recv \"%s\" after login ",rx_buf);
			return false;
		}
		else
			return true;
	}
	else
	{
		log_e(" login timeout ");
		return false;
	}	
	
}


int wm6201_send_cmd(u8 *cmd,u8 cmd_len,char *expt_ret_value,u8 *real_ret_value,u32 *ret_value_len,u32 wait_ms)
{
	u8 rx_buf[32]={0};
	u32 rx_cnt=0;
	uart_rx_fifo_clean(WM6201_UART);	
	wm6201_send(cmd,cmd_len);
	for(;wait_ms;wait_ms--)
	{
		if(wm6201_get_cmd_ack_pcket(rx_buf,&rx_cnt,sizeof(rx_buf))==false)
		{
			vTaskDelay(pdMS_TO_TICKS(1));
			continue;
		}
		if((expt_ret_value!=NULL)&&(memcmp(expt_ret_value,rx_buf,rx_cnt)==0))
		{
			return 0;
		}
		else if(expt_ret_value==NULL)
		{
			memcpy(real_ret_value,rx_buf,rx_cnt);
			*ret_value_len = rx_cnt;
			real_ret_value[rx_cnt]=0;
			return 0;			
		}
		else
		{
			memcpy(real_ret_value,rx_buf,rx_cnt);
			*ret_value_len = rx_cnt;
			return -1;
		}
	}
	return -2;
}




